package com.zoe.onelink.core.check;



import com.zoe.onelink.core.property.OnelinkProperties;
import com.zoe.onelink.core.property.http.HttpClientConfig;
import com.zoe.onelink.plugin.check.AbstractEnvironmentChecker;
import com.zoe.onelink.plugin.check.model.PropertyCheckResult;
import com.zoe.onelink.util.StrUtil;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-19
 */
public class HttpClientEnvironmentChecker extends AbstractEnvironmentChecker {

    @Override
    public List<PropertyCheckResult<?>> doCheck() {
        List<PropertyCheckResult<?>> propertyCheckResults = new ArrayList<>();
        Integer tomcatThreadMax = this.getProperty("server.tomcat.threads.max", Integer.class, -1);
        OnelinkProperties onelinkProperties = this.getBean(OnelinkProperties.class);
        HttpClientConfig httpClientProp = onelinkProperties.getHttp().getHttpClient();
        // 同步请求最大同时并发数
        int httpClientMaxRequest = httpClientProp.getMaxRequest();
        if (tomcatThreadMax > 0 && httpClientMaxRequest >= tomcatThreadMax / 2) {
            String msg = StrUtil.format("第三方请求客户端最大同步并发数为{},建议该值低于服务自身最大线程池数量[{}]的1/2及以下," +
                    "从而避免在使用同步请求第三方服务的情况下不会占用过多服务自身的线程资源", httpClientMaxRequest, tomcatThreadMax);
            PropertyCheckResult<Integer> httpClientCheck = new PropertyCheckResult<Integer>()
                    .setPropKey("onelink.http.http-client.maxRequest")
                    .setPropValue(httpClientMaxRequest)
                    .setLevel(PropertyCheckResult.Level.DANGER)
                    .setMessage(msg);
            propertyCheckResults.add(httpClientCheck);
        }

        // 单个服务最大并发数
        int maxRequestsPerHost = httpClientProp.getMaxRequestPerHost();
        if (tomcatThreadMax > 0 && maxRequestsPerHost >= httpClientMaxRequest / 2) {
            String msg = StrUtil.format("第三方请求客户端单服务最大并发数[maxRequestsPerHost={}]建议低于最大并发数[maxRequest={}]的1/2及以下," +
                    "从而避免单个第三方服务请求量过大导致其他第三方服务连接数被大量占用", maxRequestsPerHost, httpClientMaxRequest);
            PropertyCheckResult<Integer> maxReqPerHostCheck = new PropertyCheckResult<Integer>()
                    .setPropKey("onelink.http.http-client.maxRequestPerHost")
                    .setPropValue(maxRequestsPerHost)
                    .setLevel(PropertyCheckResult.Level.DANGER)
                    .setMessage(msg);
            propertyCheckResults.add(maxReqPerHostCheck);
        }
        propertyCheckResults.sort(Comparator.comparing(propertyCheckResult -> propertyCheckResult.getLevel().getVal()));
        return propertyCheckResults;
    }

}
